<!-- 作业作答页面 -->
<template>
    <div class="answer-task-page">
        <!-- <BreadCrumb type="task-answer" :list="crumbList"></BreadCrumb> -->
        <div class="answer-task-content">
            <TaskQuestion :data="taskInfo" type="task-answer"/>
            <p v-if="allTimes != -1" class="task-notice">剩余有效提交次数 <span class="orange-font">{{remainingTimes}}</span> 次</p>
            <div>
                <el-form
                    class="task-form"
                    ref="taskRef"
                    label-width="87px"
                    :model="taskInfo"
                    :rules="rules">
                    <el-form-item label="作答标题" prop="title" class="srt-el-input-item">
                        <el-input
                            class="srt-el-input w668"
                            v-model="taskInfo.title"
                            placeholder="请输入作答标题"
                            :maxlength="50"
                            show-word-limit/>
                    </el-form-item>
                    <p class="answer-notice">您可以编辑作答内容或上传附件形式提交作业，至少选择一种哦~</p>
                    <el-form-item label="作答内容" prop="answerContext" class="srt-el-input-item">
                        <el-input
                            class="srt-el-textarea w668"
                            v-model="taskInfo.answerContext"
                            placeholder="请输入作答内容"
                            type="textarea"
                            :rows="5"
                            :maxlength="500"
                            show-word-limit/>
                    </el-form-item>
                    <el-form-item label="附件" prop="answerMaterialInfoList" class="last-form-item">
                        <div>
                            <div :class="[{'mb-20': taskInfo?.answerMaterialInfoList?.length}]" v-if="!taskInfo.answerMaterialInfoList || taskInfo.answerMaterialInfoList.length < 3">
                                <el-button
                                    class="srt-el-button srt-el-button-h32 w-92"
                                    @click="materialVisible = true"
                                >选择文件</el-button>
                                <span class="upload-notice">最多3个，图片最大10M，其他文件最大500M</span>
                            </div>
                            <ul v-if="taskInfo?.answerMaterialInfoList?.length" class="task-file-list">
                                <li v-for="item in taskInfo.answerMaterialInfoList" :key="item.materialId" class="task-file-item">
                                    <FileItem type="delete" :data="item" @on-delete="deleteTask"></FileItem>
                                </li>
                            </ul>
                        </div>
                    </el-form-item>
                    <el-form-item class="option-btn-form-item">
                        <el-button
                            class="srt-el-button srt-el-button--primary srt-el-button-h32"
                            @click="onSave"
                            :loading="loading"
                            :disabled="remainingTimes <= 0 && allTimes != -1"
                            plain>
                            提交
                        </el-button>
                        <el-button
                            class="srt-el-button srt-el-button--cancel srt-el-button-h32 ml-20"
                            @click="onCancel"
                            plain>
                            取消
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <!-- 素材库 -->
        <yanxiu-material-dialog
            :mode="0"
            v-model="materialVisible"
            :category="category"
            :limit="3"
            :limit-size="limitSize"
            :selected-materials="selectedMaterials"
            usableMode="none"
            previewEnable
            showMyMaterial
            @on-ok="fileInsert"
        />
    </div>
</template>

<script setup>
import YanxiuMaterialDialog from '@/components/yanxiu-material-dialog.vue';
import TaskQuestion from './part/task-question.vue';
import { ref, computed, onBeforeMount, nextTick, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Confirm from '@/components/confirm/confirm.js';
import FileItem from './part/file-item.vue';
import { useStore } from 'vuex';
import { jumpHref } from '@/router/jumpHref.js';

const store= useStore();

const route = useRoute();

const router = useRouter();

// 面包屑
const crumbList = ref([
    {
        name: '慕课详情',
        route: {
            name: route.name === 'strainTaskAnswer' ? 'strainDetail': 'detail',
            params: {
                moocId: route.params.moocId
            },
            query: {
                tab: 'CourseAssignment'
            }
        }
    }, {
        name: '作业作答'
    }
]);

// 素材库展示的类型
const category = ['document', 'audio', 'video', 'img', 'other'];

// 作业上传附件 图片最大10M 其他最大 500M
const limitSize = {
    document: 500 * 1024 * 1024,
    audio: 500 * 1024 * 1024,
    video: 500 * 1024 * 1024,
    img: 10 * 1024 * 1024,
    other: 500 * 1024 * 1024
}


// 作业表单数据
const taskInfo = ref({
    name: '', // 作业名称
    context: '', // 作业内容
    homeWorkMaterialInfoList: [], // 作业附件
    title: '', // 作答标题
    answerContext: '', // 作答内容
    answerMaterialInfoList: [], // 作答附件
    times: 0,
    answerTimes: 0
});

const taskRef = ref(null);

// 慕课详情数据
const detailData = ref({});

// 素材库弹窗是否显示
const materialVisible = ref(false);

// 选中的素材
const selectedMaterials = computed(() => {
    console.log(4444, taskInfo.value.answerMaterialInfoList)
    return taskInfo.value.answerMaterialInfoList || [];
})

// 有效剩余提交次数
const remainingTimes = computed(() => {
    let allTimes = taskInfo.value?.times || 0;
    let answerTimes = taskInfo.value?.answerTimes || 0;
    return allTimes - answerTimes
})

// 总的提交次数
const allTimes = computed(() => {
    return taskInfo.value?.times || 0;
})

const checkTitle = (rule, value, callback) => {
    if (value && value.trim()) {
        let newVal = value.trim();
        if (newVal.length > 50 || newVal.length < 2) {
            callback(new Error('作答标题应该在2-50个字符之内！'));
        } else {
            callback();
        }
    } else {
        if (rule.required) {
            callback(new Error('请输入作答标题'));
        } else {
            callback();
        }
    }
}

const checkConetnt = (rule, value, callback) => {
    if (value && value.trim()) {
        let newVal = value.trim();
        if (newVal.length > 500 || newVal.length < 2) {
            callback(new Error('作答内容应该在2-500个字符之内！'));
        } else {
            callback();
        }
    } else {
        if (taskInfo.value.answerMaterialInfoList && taskInfo.value.answerMaterialInfoList.length) {
            callback();
        } else {
            callback(new Error('请输入作答内容或者上传附件，至少作答一项'));
        }
    }
}

const checkFile = (rule, value, callback) => {
    if (value && value.length > 3) {
        callback(new Error('最多只能添加三个作业附件！'));
    } else {
        if (value && value.length <= 3) {
            callback();
        } else {
            let context = taskInfo.value.answerContext;
            if (context && context.trim()) {
                callback();
            } else {
                callback(new Error('请输入作答内容或者上传附件，至少作答一项'));
            }
        }
        
    }
}

// 作业表单校验规则
const rules = {
    title: [{required: true, validator: checkTitle, trigger: 'blur'}],
    answerContext: [{required: false, validator: checkConetnt, trigger: 'blur'}],
    answerMaterialInfoList: [{required: false, validator: checkFile, trigger: 'change'}]
}

// 保存按钮加载状态
const loading = ref(false);


// 选中素材
function fileInsert (fileItem) {
    if (!fileItem?.length) {
        return;
    }
    taskInfo.value.answerMaterialInfoList = fileItem;
}

// 删除作业附件
function deleteTask (id) {
    taskInfo.value.answerMaterialInfoList =  taskInfo.value.answerMaterialInfoList.filter(item => item.materialId !== id)
}

// 获取作业信息
function getHomeworkInfo () {
    if (!route.query.taskId) {
        return false;
    }
    G_transmit('homeworkInfo', {
        queries: {
            homeWorkId: route.query.taskId
        }
    }).then((res) => {
        taskInfo.value = res?.data || {};
        taskInfo.value.title = res?.data?.homeWorkAnswerVO?.title || '';
        taskInfo.value.answerContext = res?.data?.homeWorkAnswerVO?.context || '';
        taskInfo.value.answerMaterialInfoList = res?.data?.homeWorkAnswerVO?.answerMaterialInfoList || [];
    })
}

// 保存/提交作业答案
function onSave () {
    taskRef.value.validate((valid) => {
        if(!valid) {
            return;
        }
        Confirm({
            title: '确认提交', 
            text: allTimes.value == -1 ? '如果该作业已经作答过将会覆盖已作答的内容' : '如果该作业已经作答过将会覆盖已作答的内容，且提交次数将会减1'
        }).then(ret => {
            answerHomework();
        })
        .catch(err => {
            // 点击取消按钮触发
            if (err === 'cancel') return false;
        })
    })
}

// 保存/提交答案
function answerHomework () {
    loading.value = true;
    let params = {
        context: taskInfo.value?.answerContext || '',
        homeworkAnswerId: taskInfo.value?.homeWorkAnswerVO?.answerId ? taskInfo.value?.homeWorkAnswerVO?.answerId : '', // 这个id是否为空来判断是保存还是更新，如果为空就是报保存，如果不为空就是更新
        homeworkId: route.query.taskId,
        materialIdList: taskInfo.value?.answerMaterialInfoList && taskInfo.value.answerMaterialInfoList.length ? taskInfo.value.answerMaterialInfoList.map(item => item.materialId) : [],
        moocId: route.params.moocId,
        name: taskInfo.value.title
    };
    G_transmit('homeworkAnswer', {
        data: params
    }).then(res => {
        G_dispatchEvent('toast', { message: allTimes.value == -1 ? '提交成功' : `提交成功，剩余提交次数 ${remainingTimes.value - 1}次`, type: 'success'});
        onCancel();
    }).finally(() => {
        loading.value = false;
    });
}

// 点击取消，跳转详情页
function onCancel () {
    G_go(crumbList.value[0].route, false);
}

const errorMsgMap = {
    'delete': '很抱歉，该慕课已下线', // 删除
    'disabled': '很抱歉，该慕课已下线', // 禁用
    'unpublished': '很抱歉，当前慕课还未发布，敬请期待', // 未发布
    'notsignup': '还未报名慕课哦，请先报名', // 没报名
    'noauthority': '很抱歉，您暂无查看权限' // 没权限
}

// 获取慕课详情
async function getDetail () {
    try {
        let res = await  G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })

        let result = res.data || {};

        detailData.value = result;

        crumbList.value[0].name = result.title;
        
        let isCourseUser = result?.isBuy; // 购买者

        let isPublish = result?.publishState == 1 && result?.state == 4;
        // 课程未发布 只有报过名的能看
        if (!isPublish && !isCourseUser) {
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.unpublished, code: 500, target: jumpHref.home.mooc(), buttonLabel: '查看其他慕课'});
        }
        // 慕课发布未报名
        if(!isCourseUser) {
           let href = router.resolve({
              ...crumbList.value[0].route
           }).href;
           G_dispatchEvent('toErrorPage', { title: errorMsgMap.notsignup, code: 500, target: href, buttonLabel: '去报名'});
        }
        setBreadCrumb();
        getHomeworkInfo();
    } catch(_err) {
        console.log(_err);
        // 禁用课程 30800500 删除课程 30800404
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.delete, code: 500, target: jumpHref.home.mooc(), buttonLabel: '查看其他慕课'});
        }  else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

onBeforeMount(async() => {
    await store.dispatch('checkIsLogout');
    getDetail();
})

// 全部备案信息
const brand = computed(() => {
    return store.state.brand && store.state.brand.publishBrand ? store.state.brand.publishBrand : {};
})

// 具体备案信息
const brandInfo = computed(() => {
    return brand.value.brandConfig ? brand.value.brandConfig : {};
})

// 面包屑
function setBreadCrumb() {
    store.dispatch('setBreadCrumb', [
        {
           ...crumbList.value[0]
        },
        {
            name: '作业作答'
        }
    ]);
}

watchEffect(() => {
    let lessonName = detailData.value?.title ? detailData.value?.title : '';
    let siteName = brandInfo.value?.siteName ? '-' + brandInfo.value?.siteName : ''
    document.title = lessonName + siteName
})
</script>

<style lang="scss" scoped>
.answer-task-page {
    .w668 {
        width: 668px;
    }
    .answer-task-content {
        width: 1200px;
        margin: 0 auto;
        background-color: #ffffff;
        border-radius: 4px;
        padding: 30px;
        min-height: 580px;
    }
    .task-notice {
        font-size: 14px;
        color: #7A5F45;
        height: 50px;
        background: #FFF8EE;
        border-radius: 4px;
        border: 1px solid #FFDDAF;
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        &::before {
            content: '\e6a8';
            color: var(--srt-color-warning);
            font-size: 24px;
            font-family: 'iconfont';
            margin: 0 10px 0 20px;
        }
        .orange-font {
            color: var(--srt-color-warning);
            margin: 0 4px;
        }
    }
    .answer-notice {
        color: var(--srt-color-gray);
        font-size: 14px;
        line-height: 15px;
        margin-bottom: 20px;
        &::before {
            content: '\e67f';
            color: var(--srt-color-warning);
            font-size: 15px;
            font-family: 'iconfont';
            margin: 0 6px 0 10px;
            // margin: 0 10px 0 20px;
        }
    }
    .task-form {
        .el-form-item {
            margin-bottom: 30px;
            :deep(.el-form-item__label) {
                color: var(--srt-color-gray);
                padding-right: 20px;
                line-height: 40px;
                white-space: nowrap;
            }
        }
        .last-form-item {
            :deep(.el-form-item__label) {
                line-height: 32px;
                white-space: nowrap;
            }
        }
        .option-btn-form-item {
            margin: 40px 0 10px 0;
        }
        .ml-20 {
            margin-left: 20px;
        }
        .mb-20 {
            margin-bottom: 20px;
        }
        .task-file-list {
            // margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
            margin-bottom: -20px;
            .task-file-item {
                width: 480px;
                margin-right: 20px;
                margin-bottom: 20px;
            }
        }
        :deep(.srt-el-textarea) {
            .el-textarea__inner {
                padding: 10px 12px;
                color: var(--srt-main-text-color);
            }
        }
    }
    .upload-notice {
        color: var(--srt-color-gray);
        font-size: 12px;
        margin-left: 10px;
    }
    .w-92 {
        width: 92px;
    }
}
</style>